import Taro, {Component} from "@tarojs/taro";
import {View, Image} from "@tarojs/components";
import {toJS} from 'mobx'
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime,partOf,pageSize} from '../../utils/common'

import './index.less'

interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class Index extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    banners: [],
    pageIndex:1,
    pageSize,
    totalCount:0,
    items:[],
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'公益活动' })
    this.getBanners()
    this.getPublicWelfare()
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  getBanners() {
    let { PublicWelfareStore }  = this.props.stores
    PublicWelfareStore.getBanners({
      callback: banners => {
        let resArr = toJS(banners)
        console.log(resArr)
        this.setState({
          banners: resArr.items
        })
      }
    })
  }

  getPublicWelfare() {
    let { pageIndex,pageSize } = this.state
    let { PublicWelfareStore }  = this.props.stores
    PublicWelfareStore.getPagedActivitiesInfo({
      pageIndex,
      pageSize,
      callback: res => {
        if (pageIndex === 1) {
          this.setState({totalCount: toJS(res.totalCount), items: toJS(res.items)})
        }else {
          const { items } = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items})
        }
      }
    })
  }
  onReachBottom(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getPublicWelfare()
      })
    }
  }

  render() {
    let { items } = this.state
    return (
      <View className='welfare-index'>
        {items.length>0&&
        <View className='list-17'>
          {
            items.map(item => {
              return(
                <View className='list-17-item' 
                onClick={this.handelRouter.bind(this, '/pages/public_welfare/activity_detail?id='+item.id)}
                key={item.id}
                >
                  <Image className='img' src={item.logoImg}/>
                  <View className='info'>
                    <View className='list-title'>{item.title}</View>
                    <View className='list-desc'>{partOf(item.introduce, 50)}</View>
                  </View>
                </View>
              )
            })
          }
        </View>
        }
        {
          items.length<=0&&<View className='page-none-info'>没有更多信息了。。。</View>
        }
      </View>
    )
  }
}

export default Index
